package common;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import java.sql.Timestamp;

import java.text.SimpleDateFormat;

import java.util.Arrays;
import java.util.Date;

import java.util.List;

import java.util.Locale;

import java.util.ResourceBundle;

import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.el.ValueExpression;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import oracle.adf.model.BindingContext;
import oracle.adf.model.binding.DCBindingContainer;
import oracle.adf.model.binding.DCIteratorBinding;

import oracle.binding.BindingContainer;
import oracle.binding.OperationBinding;

import javax.faces.application.FacesMessage.Severity;

import javax.portlet.PortletRequest;

import oracle.jbo.Row;
import oracle.jbo.RowIterator;
import oracle.jbo.domain.Number;

import org.apache.myfaces.trinidad.model.UploadedFile;

public class Utils {
    private static final String[] defaultFileExtension =
        new String[] { "doc", "docx", "xls", "xlsx", "ppt", "pptx", "odt",
                       "ods", "odp", "pdf", "zip", "rar", "txt" };
    public Utils() {
        super();
    }

    public static Locale getPortalLocale() {
        Locale portalLocale = new Locale("vi", "VN");
        String language = "";
        try {
            if (getPortletRequest().getParameter("lang") != null) {
                language = getPortletRequest().getParameter("lang");
                portalLocale = new Locale(language);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return portalLocale;
    }

    public static String getResource(String resourceKey) {
        Locale locale = getPortalLocale();
        ResourceBundle bundle =
            ResourceBundle.getBundle("portlet.PortletsBundle",
                                     locale);
        return bundle.getString(resourceKey);
    }

    public static PortletRequest getPortletRequest() {
        PortletRequest req =
            (PortletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
        return req;
    }

    public static boolean checkDefaultFileExtension(String fileName) {
        return checkFileExtension(fileName, defaultFileExtension);
    }
    
    public static boolean checkFileExtension(String fileName,
                                             String[] fileExtensions) {
        if (fileExtensions != null)
            return checkFileExtension(fileName, Arrays.asList(fileExtensions));
        return false;
    }
    
    public static boolean checkFileExtension(String fileName,
                                             List<String> listFileExtension) {
        boolean result = false;
        if (fileName != null && listFileExtension != null) {
            int index = fileName.lastIndexOf(".");
            if (index != -1) {
                String fileExtension =
                    fileName.substring(index + 1, fileName.length());
                fileExtension = fileExtension.toLowerCase();
                if (listFileExtension.contains(fileExtension)) {
                    result = true;
                }
            }
        }
        return result;
    }

    public final static Severity MSG_FATAL = FacesMessage.SEVERITY_FATAL;
    public final static Severity MSG_ERROR = FacesMessage.SEVERITY_ERROR;
    public final static Severity MSG_WARN = FacesMessage.SEVERITY_WARN;
    public final static Severity MSG_INFO = FacesMessage.SEVERITY_INFO;

    public static void showMessage(Severity severity, String sMsg) {
        FacesMessage msg = new FacesMessage(severity, null, sMsg);
        FacesContext facesContext = FacesContext.getCurrentInstance();
        facesContext.addMessage(null, msg);
        facesContext.release();
    }

    public static void showMessage(String clientId, Severity severity,
                                   String title, String sMsg) {
        FacesMessage msg = new FacesMessage(severity, title, sMsg);
        FacesContext facesContext = FacesContext.getCurrentInstance();
        facesContext.addMessage(clientId, msg);
    }

    /**
     * @comment
     * @creator thang beo
     * @param myfile
     * @param filePath
     * @param fileId
     * @return
     */
    public static Boolean fileUpload(UploadedFile myfile, File fullPath,
                                     String fileId) {
        boolean result = false;
        FileOutputStream output = null;
        try {
            if (fullPath.exists() == false) {
                fullPath.mkdirs();
            }
            byte buffer[] = new byte[1024];
            int size = 0;
            InputStream input = myfile.getInputStream();
            String fileName = myfile.getFilename();
            output =
                    new FileOutputStream(new File(fullPath, fileId + "_" + fileName));
            while ((size = input.read(buffer)) != -1) {
                output.write(buffer);
            }
            result = true;

        } catch (Exception e) {
            result = false;
            e.printStackTrace();
        } finally {
            if (output != null) {
                try {
                    output.flush();
                    output.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    /**
     * @param file
     * @param filePath
     * @param fileIterator
     * @param detailIterator
     * @param operationType
     * @param maUngDung
     */
    public static void processUpload(UploadedFile file, File filePath,
                                     String fileIterator,
                                     String detailIterator,
                                     ENUM_MA_UNG_DUNG maUngDung,
                                     String fileId) {
        DCIteratorBinding fileIterator1 =
            Utils.getIteratorBinding(fileIterator);
        DCIteratorBinding detailIterator1 =
            Utils.getIteratorBinding(detailIterator);
        fileIterator1.getCurrentRow().setAttribute("TenFile",
                                                   fileId + "_" + file.getFilename());
        fileIterator1.getCurrentRow().setAttribute("DuongDan",
                                                   filePath + "/" + fileId +
                                                   "_" + file.getFilename());
        fileIterator1.getCurrentRow().setAttribute("MaUngDung",
                                                   maUngDung.getMaUngDung());
        detailIterator1.getCurrentRow().setAttribute("FileId",
                                                     fileIterator1.getCurrentRow().getAttribute("Id"));

    }

    /**
     * @param Id
     * @param iteratorName
     * @return
     */
    public static String getValueById(String keyValue, String iteratorName) {
        String vl = null;
        if (keyValue != null) {
            DCIteratorBinding iterator1 =
                Utils.getIteratorBinding(iteratorName);
            iterator1.setCurrentRowWithKeyValue(keyValue);
            vl =
 String.valueOf(iterator1.getCurrentRow().getAttribute("TenFile"));
        }
        return vl;
    }

    /**
     * Refresh a View Iterator
     * @param iteratorName
     */
    public static void iteratorRefresh(String iteratorName) {
        try {
            DCBindingContainer dcBinding =
                (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();
            DCIteratorBinding ViewIterator =
                (DCIteratorBinding)dcBinding.get(iteratorName);
            ViewIterator.getViewObject().clearCache();
            ViewIterator.executeQuery();
            ViewIterator.refresh(DCIteratorBinding.RANGESIZE_UNLIMITED);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static List execute(String operator) {
        try {
            BindingContainer bindings = getBindings();
            OperationBinding operationBinding =
                bindings.getOperationBinding(operator);
            Object result = operationBinding.execute();
            if (operationBinding.getErrors() != null &&
                operationBinding.getErrors().size() > 0) {
                return operationBinding.getErrors();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @param el
     * @return
     */
    public static Object getElExpression(String el) {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        ELContext elContext = facesContext.getELContext();
        ExpressionFactory expressionFactory =
            facesContext.getApplication().getExpressionFactory();
        ValueExpression valueExp =
            expressionFactory.createValueExpression(elContext, el,
                                                    Object.class);
        return valueExp.getValue(elContext);
    }

    /**
     * @param el
     * @param val
     */
    public static void setElExpression(String el, Object val) {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        ELContext elContext = facesContext.getELContext();
        ExpressionFactory expressionFactory =
            facesContext.getApplication().getExpressionFactory();
        ValueExpression exp =
            expressionFactory.createValueExpression(elContext, el,
                                                    Object.class);
        exp.setValue(elContext, val);
    }

    public static oracle.jbo.domain.Date getCurrentDate() {
        SimpleDateFormat sdfDate =
            new SimpleDateFormat("dd-MM-yy"); //dd/MM/yyyy
        Date now = new Date();
        Timestamp timestamp = new Timestamp(now.getTime());
        oracle.jbo.domain.Date jboDate = new oracle.jbo.domain.Date(timestamp);
        return jboDate;
    }

    /**
     * @return
     */
    public static FacesContext getFacesContext() {
        return FacesContext.getCurrentInstance();
    }

    /**
     * @param iteratorName
     * @return
     */
    public static DCIteratorBinding getIteratorBinding(String iteratorName) {
        return getDCBindingContainer().findIteratorBinding(iteratorName);
    }

    /**
     * @return
     */
    public static DCBindingContainer getDCBindingContainer() {
        return (DCBindingContainer)getBindingContainer();
    }

    /**
     * @return
     */
    public static BindingContainer getBindingContainer() {
        return (BindingContainer)getElExpression("#{bindings}");
    }

    /**
     * @return
     */
    public static BindingContainer getBindings() {
        return BindingContext.getCurrent().getCurrentBindingsEntry();
    }

    public static enum ENUM_CAU_HINH_KHOA {
        FILE_ROOT("FILE_ROOT"),
        PAKN_DIR("PAKN_DIR"),
        PAGE_SIZE("PAGE_SIZE");
        String khoa;

        private ENUM_CAU_HINH_KHOA(String khoa) {
            this.khoa = khoa;
        }

        public String getValue(String iteratorName) {
            DCIteratorBinding it = Utils.getIteratorBinding(iteratorName);
            it.setRangeSize(-1);
            it.executeQuery();
            RowIterator rowIterator =
                it.findRowsByAttributeValues(new String[] { "Khoa" },
                                             new Object[] { khoa });
            if (rowIterator.hasNext()) {
                Row row = rowIterator.next();
                return (String)row.getAttribute("GiaTri");
            }
            return null;
        }

        private String khoaHt = "/c:/root";

        public String KHOA_HT() {
            return khoaHt;
        }

        public String getKhoa() {
            return khoa;
        }
    }

    public static enum ENUM_MA_UNG_DUNG {
        PAKN(2),
        DTVB(6);
        Number maUngDung;

        private ENUM_MA_UNG_DUNG(int maUngDung) {
            this.maUngDung = new Number(maUngDung);
        }

        public void setMaUngDung(Number maUngDung) {
            this.maUngDung = maUngDung;
        }

        public Number getMaUngDung() {
            return maUngDung;
        }
    }
}
